'use client'

import { useState, useEffect } from 'react'
import {
  Table, Button, InputNumber, Image, Typography, Card, Space,
  Checkbox, message, Popconfirm, Empty, Row, Col, Divider
} from 'antd'
import {
  DeleteOutlined, ShoppingCartOutlined, ClearOutlined,
  ShoppingOutlined
} from '@ant-design/icons'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { request } from '@/utils/request'
import { API_ENDPOINTS, IMAGE_CONFIG } from '@/utils/constants'

const { Title, Text } = Typography

interface CartItem {
  id: number;
  userId: number;
  productId: number;
  productName: string;
  productImage: string;
  productPrice: number;
  productUnit: string;
  stockQuantity: number;
  quantity: number;
  subtotal: number;
  inStock: boolean;
  createdAt: string;
  updatedAt: string;
}

export default function CartPage() {
  const [cartItems, setCartItems] = useState<CartItem[]>([])
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const router = useRouter()

  useEffect(() => {
    loadCartItems()
  }, [])

  const loadCartItems = async () => {
    setLoading(true)
    try {
      const response = await request.get(API_ENDPOINTS.CART.LIST)
      if (response.code === 200) {
        setCartItems(response.data)
        // 默认全选有库存的商品
        const inStockItems = response.data.filter((item: CartItem) => item.inStock)
        setSelectedRowKeys(inStockItems.map((item: CartItem) => item.id))
      } else {
        message.error(response.message || '加载购物车失败')
        if (response.code === 401) {
          router.push('/login')
        }
      }
    } catch (error: any) {
      message.error(error.message || '加载购物车失败')
      if (error.message.includes('401')) {
        router.push('/login')
      }
    } finally {
      setLoading(false)
    }
  }

  const updateQuantity = async (productId: number, quantity: number) => {
    try {
      const response = await request.put(`${API_ENDPOINTS.CART.UPDATE}?productId=${productId}&quantity=${quantity}`)
      if (response.code === 200) {
        message.success('更新成功')
        await loadCartItems() // 重新加载购物车
      } else {
        message.error(response.message || '更新失败')
      }
    } catch (error: any) {
      message.error(error.message || '更新失败')
    }
  }

  const removeItem = async (productId: number) => {
    try {
      const response = await request.delete(`${API_ENDPOINTS.CART.REMOVE}?productId=${productId}`)
      if (response.code === 200) {
        message.success('已移除')
        await loadCartItems()
      } else {
        message.error(response.message || '移除失败')
      }
    } catch (error: any) {
      message.error(error.message || '移除失败')
    }
  }

  const clearCart = async () => {
    try {
      const response = await request.delete(API_ENDPOINTS.CART.CLEAR)
      if (response.code === 200) {
        message.success('购物车已清空')
        setCartItems([])
        setSelectedRowKeys([])
      } else {
        message.error(response.message || '清空失败')
      }
    } catch (error: any) {
      message.error(error.message || '清空失败')
    }
  }

  const handleCheckout = () => {
    const selectedItems = cartItems.filter(item => selectedRowKeys.includes(item.id))
    if (selectedItems.length === 0) {
      message.warning('请选择要结算的商品')
      return
    }
    
    const outOfStockItems = selectedItems.filter(item => !item.inStock)
    if (outOfStockItems.length > 0) {
      message.warning('选中的商品中有库存不足的商品，请重新选择')
      return
    }

    // 将选中的商品信息传递给结算页面
    const orderData = {
      items: selectedItems.map(item => ({
        productId: item.productId,
        quantity: item.quantity
      }))
    }
    
    // 将数据存储到sessionStorage
    sessionStorage.setItem('checkoutData', JSON.stringify(orderData))
    router.push('/checkout')
  }

  const columns = [
    {
      title: '商品信息',
      key: 'product',
      render: (record: CartItem) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <Image
            width={60}
            height={60}
            src={record.productImage || IMAGE_CONFIG.DEFAULT_PRODUCT}
            alt={record.productName}
            style={{ borderRadius: '4px', objectFit: 'cover' }}
          />
          <div>
            <Link href={`/products/${record.productId}`}>
              <Text strong style={{ fontSize: '16px' }}>{record.productName}</Text>
            </Link>
            <br />
            <Text type="secondary">单价：￥{record.productPrice.toFixed(2)}/{record.productUnit}</Text>
          </div>
        </div>
      ),
    },
    {
      title: '库存状态',
      key: 'stock',
      width: 120,
      render: (record: CartItem) => (
        <div>
          {record.inStock ? (
            <Text type="success">有库存</Text>
          ) : (
            <Text type="danger">库存不足</Text>
          )}
          <br />
          <Text type="secondary">剩余{record.stockQuantity}{record.productUnit}</Text>
        </div>
      ),
    },
    {
      title: '数量',
      key: 'quantity',
      width: 150,
      render: (record: CartItem) => (
        <InputNumber
          min={1}
          max={record.stockQuantity}
          value={record.quantity}
          onChange={(value) => {
            if (value && value !== record.quantity) {
              updateQuantity(record.productId, value)
            }
          }}
          disabled={!record.inStock}
        />
      ),
    },
    {
      title: '小计',
      key: 'subtotal',
      width: 120,
      render: (record: CartItem) => (
        <Text strong style={{ fontSize: '16px', color: '#ff4d4f' }}>
          ￥{record.subtotal.toFixed(2)}
        </Text>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (record: CartItem) => (
        <Popconfirm
          title="确定要移除这个商品吗？"
          onConfirm={() => removeItem(record.productId)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="text" danger icon={<DeleteOutlined />}>
            移除
          </Button>
        </Popconfirm>
      ),
    },
  ]

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys)
    },
    getCheckboxProps: (record: CartItem) => ({
      disabled: !record.inStock,
    }),
  }

  // 计算选中商品的总价
  const selectedItems = cartItems.filter(item => selectedRowKeys.includes(item.id))
  const totalAmount = selectedItems.reduce((sum, item) => sum + item.subtotal, 0)
  const totalQuantity = selectedItems.reduce((sum, item) => sum + item.quantity, 0)

  if (cartItems.length === 0 && !loading) {
    return (
      <div style={{ padding: '20px', minHeight: '100vh', background: '#f5f5f5' }}>
        <Card>
          <Empty
            image={<ShoppingCartOutlined style={{ fontSize: '64px', color: '#d9d9d9' }} />}
            description={
              <div>
                <Text style={{ fontSize: '18px' }}>购物车是空的</Text>
                <br />
                <Text type="secondary">去挑选一些优质的海产品吧！</Text>
              </div>
            }
          >
            <Link href="/products">
              <Button type="primary" size="large" icon={<ShoppingOutlined />}>
                去购物
              </Button>
            </Link>
          </Empty>
        </Card>
      </div>
    )
  }

  return (
    <div style={{ padding: '20px', minHeight: '100vh', background: '#f5f5f5' }}>
      <Title level={2} style={{ marginBottom: '20px' }}>
        <ShoppingCartOutlined /> 购物车
      </Title>

      <Card>
        {/* 购物车列表 */}
        <Table
          columns={columns}
          dataSource={cartItems}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={false}
          locale={{ emptyText: '购物车为空' }}
        />

        {cartItems.length > 0 && (
          <>
            <Divider />
            
            {/* 操作按钮 */}
            <Row justify="space-between" align="middle">
              <Col>
                <Space>
                  <Checkbox
                    checked={selectedRowKeys.length === cartItems.filter(item => item.inStock).length && cartItems.filter(item => item.inStock).length > 0}
                    indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < cartItems.filter(item => item.inStock).length}
                    onChange={(e) => {
                      const inStockItems = cartItems.filter(item => item.inStock)
                      if (e.target.checked) {
                        setSelectedRowKeys(inStockItems.map(item => item.id))
                      } else {
                        setSelectedRowKeys([])
                      }
                    }}
                  >
                    全选
                  </Checkbox>
                  
                  <Popconfirm
                    title="确定要清空购物车吗？"
                    onConfirm={clearCart}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button icon={<ClearOutlined />}>
                      清空购物车
                    </Button>
                  </Popconfirm>
                </Space>
              </Col>
              
              <Col>
                <Space size="large">
                  <div>
                    <Text>已选择 </Text>
                    <Text strong style={{ color: '#1890ff' }}>{selectedRowKeys.length}</Text>
                    <Text> 件商品，共 </Text>
                    <Text strong style={{ color: '#1890ff' }}>{totalQuantity}</Text>
                    <Text> 件</Text>
                  </div>
                  
                  <div>
                    <Text>合计：</Text>
                    <Text strong style={{ fontSize: '20px', color: '#ff4d4f' }}>
                      ￥{totalAmount.toFixed(2)}
                    </Text>
                  </div>
                  
                  <Button 
                    type="primary" 
                    size="large"
                    onClick={handleCheckout}
                    disabled={selectedRowKeys.length === 0}
                  >
                    结算({selectedRowKeys.length})
                  </Button>
                </Space>
              </Col>
            </Row>
          </>
        )}
      </Card>
    </div>
  )
}